import random
import coreapi
import requests
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.conf import settings
from rest_framework.decorators import (
        api_view, schema, action, permission_classes
        )
from rest_framework.response import Response
from rest_framework import viewsets, permissions
from hony.models import AuthorModel, ArticleModels, StationModel

from hony.serializers import AuthorSerializer, ArticleSerializer


# Create your views here.

@api_view(["GET"])
def get_password(request, num=None, *arges, **kwarges):
    msg = [str(_) for _ in range(10)] + [chr(_) for _ in range(65, 91)] + [chr(_) for _ in range(97, 123)]
    passwd = ''
    if num:
        for _ in range(num):
           passwd += random.choice(msg)
    else:
        return Response(data="需要指定密码长度")
    return Response(data=passwd)
    

class AuthorViews(viewsets.ModelViewSet):
    queryset = AuthorModel.objects.all()
    serializer_class = AuthorSerializer
    

class ArticleViews(viewsets.ModelViewSet):
    queryset = ArticleModels.objects.all()
    serializer_class = ArticleSerializer


class ArticleDetailView(DetailView):
    queryset = ArticleModels.objects.filter(enabled=True)
    template_name = 'info.html'

    def get_context_data(self, **kwargs):
        crumbs = []
        queryset = self.get_queryset()
        if self.object.station:
            crumbs.append(self.object.station)
            queryset = queryset.filter(station=self.object.station)
        if self.object.series:
            crumbs.append(self.object.series)
            queryset = queryset.filter(series=self.object.series)
        instance = self.object
        instance.name = self.object.title
        crumbs.append(instance)
        next_qs = queryset.filter(series_sort__gt=self.object.series_sort).order_by("series_sort")
        previous_qs = queryset.filter(series_sort__lt=self.object.series_sort).order_by("-series_sort")
        context = {
            "previous": previous_qs.first() if previous_qs.exists() else None,
            "next": next_qs.first() if next_qs.exists() else None,
            "stations": StationModel.objects.filter(enabled=True),
            "title": self.object.title,
            "summary": self.object.content[:20] if self.object.content != '-1' else self.object.articlecontentmodel.content[:20],
            "crumbs": crumbs
        }
        return super().get_context_data(**context)
